package cn.nubia.admin.application.service;

import cn.nubia.admin.application.bean.AdItem;
import cn.nubia.admin.application.bean.Channel;
import cn.nubia.admin.application.query.ChannelQuery;
import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.common.utils.DateUtil;
import cn.nubia.admin.sysconfig.bean.SystemLog;
import cn.nubia.admin.sysconfig.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by justin on 15/7/11.
 */
@Service
public class ChannelService extends BaseServiceImpl<Channel> {
    @Autowired
    SystemLogService systemLogService;

    public Paged<Channel> listChannels(ChannelQuery channelQuery) {
        Query<Channel> query = Query.build(Channel.class);
        if(channelQuery.getChannelName()!=null&&channelQuery.getChannelName()!=""){
            query.addLike(Channel.COLUMN_CHANNELNAME,channelQuery.getChannelName());
        }
        query.addNotEq(Channel.COLUMN_STATE,Channel.STATE_DEL);
        query.addOrder(Channel.COLUMN_LASTMODIFYTIME, Query.DBOrder.DESC);
        query.setPaged(channelQuery.getPageNo(), channelQuery.getPageSize());
        return findPagedByQuery(query);
    }

    public void processSaveChannel(Channel channel) {
        Integer curr = DateUtil.getCurrentTime();
        if(channel.getId()==null||channel.getId()<1){
            channel.setLastModifyTime(curr);
            insert(channel);
            //log
            systemLogService.log(SystemLog.ModuleTypeEnum.CHANNELLIST, SystemLog.OperateTypeEnum.EDIT, channel.getId());
        }else{
            channel.setLastModifyTime(curr);
            update(channel);
            //log
            systemLogService.log(SystemLog.ModuleTypeEnum.CHANNELLIST, SystemLog.OperateTypeEnum.EDIT, channel.getId());
        }
    }

    public Channel changeState(Integer id,Integer state) {
        Channel channel = get(id);
        channel.setState(state);
        update(channel);
        //log
        if(state == Channel.STATE_DEL){
            systemLogService.log(SystemLog.ModuleTypeEnum.CHANNELLIST, SystemLog.OperateTypeEnum.DEL, id);
        }else if(state == Channel.STATE_HIDDEN){
            systemLogService.log(SystemLog.ModuleTypeEnum.CHANNELLIST, SystemLog.OperateTypeEnum.HIDDEN, id);
        }else if(state == Channel.STATE_SHOW){
            systemLogService.log(SystemLog.ModuleTypeEnum.CHANNELLIST, SystemLog.OperateTypeEnum.SHOW, id);
        }
        return channel;
    }
}
